package utils;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;

public class SocketConnectUtils {
    public static Socket getSocketByHost(String host, boolean isSSL){
        Socket socket = null;
        InetAddress address = null;
        int port = -1;
        try {
            if(host.contains(":")){
                address = InetAddress.getByName(host.substring(0, host.indexOf(":")));
                port = Integer.parseInt(host.substring(host.indexOf(":") + 1));
            }else{
                address = InetAddress.getByName(host);
            }

            if (isSSL){
                SSLContext sslContext = SSLContextUtil.getSSLContext();
                SSLSocket sslSocket = (SSLSocket)sslContext.getSocketFactory().createSocket(address, port == -1 ? Integer.parseInt(Consts.getProp("redirectSSLPort")) : port);
                sslSocket.startHandshake();
                socket = sslSocket;
            }else{
                socket = new Socket(address, port == -1 ? Integer.parseInt(Consts.getProp("redirectPort")) : port);
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }

        return socket;
    }

    public static void byteTransfer(InputStream source, OutputStream target, int length) throws IOException{
        byte[] buffer = new byte[100000];
        int count = 0;
        int bytesRead = 0;

        //这里访问公司平台的时候，不知道为啥数据传输完了但是服务器一直没有返回-1而是一直读取到0，导致卡在这里了
        while(count < length && (bytesRead = source.read(buffer)) != -1){
            target.write(buffer, 0, bytesRead);
            count += bytesRead;
        }
    }

    public static void byteTransfer(InputStream source, OutputStream target) throws IOException{
        byte[] buffer = new byte[100000];
        int bytesRead = 0;

        while((bytesRead = source.read(buffer)) != -1){
            target.write(buffer, 0, bytesRead);
        }
    }
}
